import { ApiResult, News } from '@/types';
import { Module } from 'vuex';
import {getNewsList}  from '../../api/news';

interface State{
    newsList: News[];
    currentPage: number;
}

export default <Module<State,any>>{
    //是否局部化该子状态模块，参见vuex官方文档的modules节
    namespaced: true,
    state: {
        //新闻列表数据
        newsList: [],
        //当前页码数据
        currentPage:1
    },
    mutations: {
        //通过更改state的值，更新界面显示
        updateNewsList(state, {page, list}) {
            state.newsList = list;
            state.currentPage = page;
        },
        updateNews(state, {index, newData}){
            state.newsList.splice(index, 1, newData);
        }
    },
    actions: {
        //此方法的其中一个调用者为src/views/mysample/NewsList.vue
        //执行一些异步逻辑，待完成时调用同步的updateNewsList方法更新状态
        async getNewsList({ commit }, {page, count}) {
            //调用后端接口访问方法获取数据，参见src/api/news.js
            let newsList: News[]
            try{
                const r = await getNewsList(page, count);
                newsList = r.data.result;
            }
            catch(error){
                newsList = [
                    {
                        "path": "https://dy.163.com/article/FRF5C6SS0521POG7.html",
                        "title": "测试新闻1",
                    },
                    {
                        "path": "https://dy.163.com/article/FRHPT70H051481US.html",
                        "title": "测试新闻2",
                    },
                    {
                        "path": "https://news.163.com/20/1116/07/FRHPBAPJ0001899O.html",
                        "title": "测试新闻3",
                    }
                ]
            }
            //提交给同步方法updateNewsList进行状态更新
            commit('updateNewsList', {page, count, list:newsList});
        }
    }
}